package com.fire.chat.config;

import com.fire.chat.annotation.EnableAuthority;
import com.fire.chat.aspect.AuthorityAspect;
import com.fire.chat.enums.CacheStrategyEnum;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.support.BeanDefinitionRegistry;
import org.springframework.beans.factory.support.GenericBeanDefinition;
import org.springframework.context.annotation.ImportBeanDefinitionRegistrar;
import org.springframework.core.annotation.AnnotationAttributes;
import org.springframework.core.type.AnnotationMetadata;
import org.springframework.core.type.StandardAnnotationMetadata;

/**
 * @program: hxzq
 * @description: 鉴权服务注册配置 TODO 目前就简单一点,后续有时间再优化提高扩展性
 * @author: xjr
 * @create: 2020-11-05 17:09
 **/
@Slf4j
public class AuthorityBeanRegister implements ImportBeanDefinitionRegistrar {
    @Override
    public void registerBeanDefinitions(AnnotationMetadata annotationMetadata, BeanDefinitionRegistry beanDefinitionRegistry) {
        StandardAnnotationMetadata standardAnnotationMetadata = (StandardAnnotationMetadata)annotationMetadata;
        AnnotationAttributes annotationMap = AnnotationAttributes.fromMap(annotationMetadata.getAnnotationAttributes(EnableAuthority.class.getName()));
        if (annotationMap.getBoolean("active")){
            GenericBeanDefinition cacheBeanDefinition=new GenericBeanDefinition();
            cacheBeanDefinition.setBeanClass(((CacheStrategyEnum)annotationMap.getEnum("cacheStrategy")).cache());
            cacheBeanDefinition.setScope("singleton");
            GenericBeanDefinition aspectBeanDefinition = new GenericBeanDefinition();
            aspectBeanDefinition.setBeanClass(AuthorityAspect.class);
            aspectBeanDefinition.setScope("singleton");
            beanDefinitionRegistry.registerBeanDefinition("authorityCacheBean",cacheBeanDefinition);
            beanDefinitionRegistry.registerBeanDefinition("authorityAspect",aspectBeanDefinition);
        }

    }
}
